﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Net.Sockets;
using System.Net;

namespace Server
{
    
    public partial class FormServer : Form
    {
        private Thread listenThread;
        static private bool m_bListening = false;
        static private System.Net.IPAddress MyIP = System.Net.IPAddress.Parse("127.0.0.1");
        static private TcpListener listener = new TcpListener(MyIP, 5567);

        public  delegate void UpdateMessage(string str);

        public FormServer()
        {
            InitializeComponent();   
        }

        private void showClientMessage(string msg)
        {
            this.richTextBox1.Text = msg;
        }

        private void startListen()
        {
            #region tcpclient class
            /*
            listener.Start();
            //接收数据
            while (m_bListening)
            {
                //测试是否有数据
                try
                {
                    TcpClient client = listener.AcceptTcpClient();
                    NetworkStream ns = client.GetStream();

                    //字组处理
                    byte[] bytes = new byte[1024];
                    int bytesread = ns.Read(bytes, 0, bytes.Length);
                    string msg = Encoding.Default.GetString(bytes, 0, bytesread);

                    if (this.richTextBox1.InvokeRequired)
                    {
                        UpdateMessage updateMessage = new UpdateMessage(showClientMessage);
                        this.richTextBox1.Invoke(updateMessage, msg);
                    }
                    else
                    {
                        showClientMessage(msg);
                    }

                    ns.Close();
                    client.Close();
                    //清场

                }
                catch (Exception re)
                {
                    MessageBox.Show(re.Message);
                }

                listener.Stop();
            }
            */
            #endregion

            #region socket communication
            try
            {
                
                int port = 2000;
                string host = "127.0.0.1";
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);
                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket类
                s.Bind(ipe);//绑定2000端口
                s.Listen(0);//开始监听
                while (m_bListening)
                {
                    Socket temp = s.Accept();//为新建连接创建新的Socket。
                    string recvStr = "";
                    byte[] recvBytes = new byte[1024];
                    int bytes;
                    bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
                    
                    //recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);

                    recvStr += Encoding.Unicode.GetString(recvBytes, 0, bytes); //读取中文字符

                    if (this.richTextBox1.InvokeRequired)
                    {
                        UpdateMessage updateMessage = new UpdateMessage(showClientMessage);
                        this.richTextBox1.Invoke(updateMessage, recvStr);
                    }
                    else
                    {
                        showClientMessage(recvStr);
                    }

                    ReplyToClient(temp);
                    temp.Close();
                }
                
                s.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            #endregion
        }

        private void ReplyToClient(Socket temp)
        {
            string sendStr = "Ok!Server Receive Message Sucessful!";
            //byte[] bs = Encoding.ASCII.GetBytes(sendStr);
            byte[] bs = Encoding.Unicode.GetBytes(sendStr);
            temp.Send(bs, bs.Length, 0);//返回客户端成功信息
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            if (m_bListening)
            {
            }
            else
            {
                m_bListening = true;
                listenThread = new Thread(new ThreadStart(startListen));
                listenThread.Start();
                listenThread.IsBackground = true;
                listenThread.Name = "server";
                labelStatus.Text = "Listening...";
            }
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            if (m_bListening)
            {
                m_bListening = false;
                labelStatus.Text = "Idle";

                if (listenThread.IsAlive)
                {
                    listenThread.Abort();
                }
            }
        }
    }
}
